package com.diamond.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class MD5 {
	/**
	 * @param input
	 * @return
	 * @throws Exception
	 */
	private final static String mykey = "ABCTEFIXGH";
	private final static String defaultPwdE = "dia1111";     //管理员用户
	private final static String defaultPwdB = "dia2222";     //总代理用户
	private final static String defaultPwdC = "dia3333";     // 经销商用户
	private final static String defaultPwdD = "000000";      //经销商子用户
	
	public static String encode(String input) {
		try {
			if(StringUtil.isEmpty(input))return null;
			SecureRandom sr = new SecureRandom();
			byte rawKeyData[] = mykey.getBytes();
			DESKeySpec dks = new DESKeySpec(rawKeyData);

			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey key = keyFactory.generateSecret(dks);

			Cipher c = Cipher.getInstance("DES");
			c.init(Cipher.ENCRYPT_MODE, key, sr);
			byte[] cipherByte = c.doFinal(input.getBytes());
			String dec = new BASE64Encoder().encode(cipherByte);
			return dec;
		} catch (Exception e) {
			return null;
		}

	}

	/**
	 * @param input
	 * @return
	 * @throws Exception
	 */
	public static String decode(String input) {
		try {
			if(StringUtil.isEmpty(input))return null;
			byte[] dec = new BASE64Decoder().decodeBuffer(input);

			SecureRandom sr = new SecureRandom();
			byte rawKeyData[] = mykey.getBytes();

			DESKeySpec dks = new DESKeySpec(rawKeyData);

			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

			SecretKey key = keyFactory.generateSecret(dks);

			Cipher c = Cipher.getInstance("DES");
			c.init(Cipher.DECRYPT_MODE, key, sr);
			byte[] clearByte = c.doFinal(dec);
			return new String(clearByte);
		} catch (Exception e) {
			return null;
		}

	}
	
	public static Boolean valid(String passStr,String pass){
		if(StringUtil.isEmpty(passStr)||StringUtil.isEmpty(pass))return false;
		if(encode(passStr).equals(pass))return true;
		return false;
	}

	public static String getDefaultPwdE() {
		return MD5.encode(defaultPwdE);
	}

	public static String getDefaultPwdB() {
		return MD5.encode(defaultPwdB);
	}

	public static String getDefaultPwdC() {
		return MD5.encode(defaultPwdC);
	}

	public static String getDefaultPwdD() {
		return MD5.encode(defaultPwdD);
	}

	public static void main(String[] args) throws Exception {
		String str = "1111";
		String code = encode(str);
		String init = decode(code);
		System.out.println(code);
		System.out.println(init);
		System.out.println(valid(str,code));
	}

}
